//
//  YBRechargeVC.m
//  WuyouTang
//
//  Created by YB007 on 2019/11/20.
//  Copyright © 2019 cat. All rights reserved.
//

#import "YBRechargeVC.h"

#import "PubH5.h"
#import "YBRechargeType.h"
@interface YBRechargeVC (){
    UILabel *coinL;
    UIImageView *headerImgV;
    NSDictionary *subDic;
    NSArray *allArray;
    UIScrollView *backScroll;
    NSMutableArray *payTypeArray;
    NSMutableArray *coinArray;
    
    NSString *payTypeID;
    BOOL isCreatUI;
    NSDictionary *payTypeSelDic;
}
@property(nonatomic,strong)NSDictionary *seleDic;//选中的钻石字典
//支付宝
@property(nonatomic,copy)NSString *aliapp_key_ios;
@property(nonatomic,copy)NSString *aliapp_partner;
@property(nonatomic,copy)NSString *aliapp_seller_id;
//微信
@property(nonatomic,copy)NSString *wx_appid;

@end

@implementation YBRechargeVC

- (void)viewWillAppear:(BOOL)animated{
    [self requestData];

}
- (void)clickNaviLeftBtn {
    [super clickNaviLeftBtn];
    [[YBRechargeType chargeManeger]removePayNotice];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)dealloc {
    [[YBRechargeType chargeManeger]removePayNotice];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)clickNaviRightBtn
{
    NSString *url =[NSString stringWithFormat:@"%@/appapi/charge/index",h5url];
    PubH5 *VC = [[PubH5 alloc]init];
    VC.url =[h5url stringByAppendingString:[NSString stringWithFormat:@"/appapi/charge/index?uid=%@&token=%@",[Config getOwnID],[Config getOwnToken]]];
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:VC animated:YES];

}

-(void)appactive {
    [self requestData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //支付监听
    [[YBRechargeType chargeManeger]addPayNotice];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appactive) name:UIApplicationDidBecomeActiveNotification object:nil];

    self.titleL.text = YZMsg(@"我的钱包");
    self.rightBtn.hidden = NO;
    [self.rightBtn setImage:[UIImage imageNamed:@"recharge_明细"] forState:0];
    
    payTypeArray = [NSMutableArray array];
    coinArray = [NSMutableArray array];

    backScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight-60-ShowDiff)];
    [self.view addSubview:backScroll];
    backScroll.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestData];
    }];

    headerImgV = [[UIImageView alloc]initWithFrame:CGRectMake(15, 10, _window_width-30, (_window_width-30)*0.38)];
    headerImgV.userInteractionEnabled = YES;
    headerImgV.image = [UIImage imageNamed:@"recharge_背景"];
    [backScroll addSubview:headerImgV];
    UILabel *labelll = [[UILabel alloc]init];
    labelll.textColor = [UIColor whiteColor];
    labelll.font = SYS_Font(12);
    labelll.text = [NSString stringWithFormat:@"%@%@",YZMsg(@"我的"),[common name_coin]];
    [headerImgV addSubview:labelll];
    [labelll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(headerImgV);
        make.centerY.equalTo(headerImgV).multipliedBy(0.65);
    }];
    coinL = [[UILabel alloc]init];
    coinL.textColor = [UIColor whiteColor];
    coinL.font = [UIFont boldSystemFontOfSize:28];
    coinL.text = @"0";
    [headerImgV addSubview:coinL];
    [coinL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(headerImgV);
        make.centerY.equalTo(headerImgV).multipliedBy(1.11);
    }];
    
    YBButton *youngBtn = [PublicObj youngAlertBtn];
    [self.view addSubview:youngBtn];
    [youngBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(backScroll);
        make.top.equalTo(backScroll.mas_bottom).offset(10);
    }];
    
    NSString *xieyiStr = YZMsg(@"《用户充值协议》");
    UILabel *label = [[UILabel alloc] init];
    label.text = [NSString stringWithFormat:@"%@%@",YZMsg(@"已阅读并同意"),xieyiStr];
    label.textColor = RGB_COLOR(@"#646464", 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(backScroll);
        make.top.equalTo(youngBtn.mas_bottom).offset(5);
    }];
    NSRange range = [label.text rangeOfString:xieyiStr];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text];
    [str addAttribute:NSForegroundColorAttributeName value:Pink_Cor range:range];
    label.attributedText = str;
    label.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(eula)];
    [label addGestureRecognizer:tap];

    

}
- (void)requestData{

    [WYNetworking postWithUrl:@"User.getBalance" Dic:@{@"type":@"0"} Suc:^(int code, id info, NSString *msg) {
        [backScroll.mj_header endRefreshing];
        if (code == 0) {
            NSDictionary *infoDic = [info firstObject];
            coinL.text = minstr([infoDic valueForKey:@"coin"]);
            [Config saveUserCoin:minstr([infoDic valueForKey:@"coin"])];
            if (self.block) {
                self.block(minstr([infoDic valueForKey:@"coin"]));
            }
            if (allArray.count == 0) {
                _aliapp_key_ios = [infoDic valueForKey:@"aliapp_key_ios"]?[infoDic valueForKey:@"aliapp_key_ios"]:minstr([infoDic valueForKey:@"aliapp_key"]);
                _aliapp_partner = minstr([infoDic valueForKey:@"aliapp_partner"]);
                _aliapp_seller_id = minstr([infoDic valueForKey:@"aliapp_seller_id"]);
                //微信的信息
                _wx_appid = [infoDic valueForKey:@"wx_appid"];
                
                NSArray *ssssss = [infoDic valueForKey:@"paylist"];
                NSArray *rulesA = [infoDic valueForKey:@"rules"];
                if ([PublicObj isUp]) {
                    /// 充值规则中可能包含充值优惠,上架期间剔除
                    NSMutableArray *m_a = [NSMutableArray array];
                    for (NSDictionary *subDic in rulesA) {
                        int r_m = [minstr([subDic valueForKey:@"money"]) intValue];
                        if (r_m > 6) {
                            [m_a addObject:subDic];
                        }
                    }
                    rulesA = [NSArray arrayWithArray:m_a];
                }
                if (ssssss.count > 0) {
                    allArray = @[ssssss,rulesA];
                    if (!isCreatUI) {
                        [self creatUI];
                    }
                }
            }
        }
    } Fail:^(id fail) {
        [backScroll.mj_header endRefreshing];
    }];

}
- (void)creatUI{
    isCreatUI = YES;
    CGFloat btnWidth;
    CGFloat btnHeight;
    CGFloat btnSH = 0.0;
    if (IS_IPHONE_5) {
        btnWidth = 90;
        btnHeight = 41;
        btnSH = 49;
    }else{
        btnWidth = 110;
        btnHeight = 50;
        btnSH = 60;
    }
    CGFloat speace = (_window_width-30-btnWidth*3)/2;
    CGFloat y = headerImgV.bottom + 20;
    for (int i = 0; i < allArray.count; i++) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, y, 100, 20)];
        label.font = SYS_Font(12);
        label.textColor = RGB_COLOR(@"#ffffff", 0.6);
        NSArray *array = allArray[i];
        [backScroll addSubview:label];
        if (i == 0) {
            if (array.count == 0) {
                payTypeID = @"";
                continue;
            }
            if (array.count == 1 && [minstr([array[0] valueForKey:@"id"]) isEqual:@"apple"]) {
                payTypeID = @"apple";
                continue;
            }
            label.text = YZMsg(@"请选择支付方式");
            
            YBButton *youngBtn = [PublicObj youngAlertBtn];
            [backScroll addSubview:youngBtn];
            [youngBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.height.centerY.equalTo(label);
                make.right.equalTo(self.view.mas_right).offset(-15);
            }];
            
            for (int j = 0; j < array.count; j++) {
                UIButton *btn = [UIButton buttonWithType:0];
                btn.backgroundColor = CellRow_Cor;
                btn.frame = CGRectMake(15+j%3 * (btnWidth+speace), label.bottom+10+(j/3)*(btnHeight + 30), btnWidth, btnHeight);
                [btn addTarget:self action:@selector(payTypeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                [btn setBackgroundImage:[UIImage imageNamed:@""] forState:0];
                [btn setBackgroundImage:[UIImage imageNamed:@"recharge_sel"] forState:UIControlStateSelected];
                [backScroll addSubview:btn];
                if (j == 0) {
                    btn.selected = YES;
                    payTypeID = minstr([array[j] valueForKey:@"id"]);
                }
                btn.tag = 1000+j;
                UILabel *titleL = [[UILabel alloc]init];
                titleL.font = SYS_Font(13);
                titleL.textColor = RGB_COLOR(@"#ffffff", 1);
                titleL.text = minstr([array[j] valueForKey:@"name"]);
                [btn addSubview:titleL];
                [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(btn);
                    make.centerX.equalTo(btn).multipliedBy(1.21);
                }];
                UIImageView *imgV = [[UIImageView alloc]init];
                [imgV sd_setImageWithURL:[NSURL URLWithString:minstr([array[j] valueForKey:@"thumb"])]];
                [btn addSubview:imgV];
                [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(btn);
                    make.height.width.mas_equalTo(16);
                    make.right.equalTo(titleL.mas_left).offset(-5);
                }];
                [payTypeArray addObject:btn];
                if (j == array.count-1) {
                    [backScroll layoutIfNeeded];
                    y = btn.bottom + 20;
                }
            }

        }else{
            label.text = YZMsg(@"请选择充值金额");
            for (int j = 0; j < array.count; j++) {
                UIButton *btn = [UIButton buttonWithType:0];
                btn.backgroundColor = CellRow_Cor;
                btn.frame = CGRectMake(15+j%3 * (btnWidth+speace), label.bottom+10+(j/3)*(btnSH + 30), btnWidth, btnSH);
                [btn addTarget:self action:@selector(coinBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                btn.clipsToBounds = NO;
                btn.layer.cornerRadius = 5;
                btn.layer.masksToBounds = YES;
                btn.layer.borderWidth = 1;
                btn.tag = 2000+j;
                [backScroll addSubview:btn];
                NSString *give = minstr([array[j] valueForKey:@"give"]);
                if (![give isEqual:@"0"]) {
                    CGFloat widddth = [PublicObj sizeWithString:[NSString stringWithFormat:@"%@%@%@",YZMsg(@"赠送"),give,[common name_coin]] andFont:SYS_Font(10)].width;
                    UIImageView *giveImgV = [[UIImageView alloc]initWithFrame:CGRectMake(btn.right-widddth-5, btn.top-7.5, widddth+10, 20)];
                    giveImgV.image = [UIImage imageNamed:@"recharge_send"];
                    [backScroll addSubview:giveImgV];
                    UILabel *giveLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, widddth, 15)];
                    giveLabel.text = [NSString stringWithFormat:@"%@%@%@",YZMsg(@"赠送"),give,[common name_coin]];
                    giveLabel.font = SYS_Font(10);
                    giveLabel.textColor = [UIColor whiteColor];
                    [giveImgV addSubview:giveLabel];
                }
//                if (j == 0) {
                btn.layer.borderColor = [UIColor clearColor].CGColor;
//                }
                UILabel *titleL = [[UILabel alloc]init];
                titleL.font = SYS_Font(15);
                titleL.textColor = RGB_COLOR(@"#ffffff", 1);
                titleL.text = minstr([array[j] valueForKey:@"coin"]);
                if ([payTypeID isEqual:@"apple"]) {
                    titleL.text = minstr([array[j] valueForKey:@"coin_ios"]);
                }
                titleL.tag = btn.tag + 3000;
                [btn addSubview:titleL];
                [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(btn).multipliedBy(0.73);
                    make.centerX.equalTo(btn);
                }];
                UIImageView *imgV = [[UIImageView alloc]init];
                imgV.image = [UIImage imageNamed:@"礼物-金币"];
                [btn addSubview:imgV];
                [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(titleL);
                    make.height.width.mas_equalTo(12);
                    make.left.equalTo(titleL.mas_right).offset(5);
                }];
                UILabel *moneyL = [[UILabel alloc]init];
                moneyL.font = SYS_Font(12);
                moneyL.textColor = RGB_COLOR(@"#ffffff", 1);
                moneyL.tag = btn.tag +4000;
                moneyL.text = [NSString stringWithFormat:@"¥%@",minstr([array[j] valueForKey:@"money"])];
                [btn addSubview:moneyL];
                [moneyL mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(btn).multipliedBy(1.3);
                    make.centerX.equalTo(btn);
                }];
                [coinArray addObject:btn];
                if (j == array.count-1) {
                    [backScroll layoutIfNeeded];
                    y = btn.bottom + 20;
                }

            }

        }
    }
    CGFloat bottomLY;
    if (y > backScroll.height - 40 -ShowDiff) {
        bottomLY = y + 40;
    }else{
        bottomLY = backScroll.height - 40 -ShowDiff;
    }
    backScroll.contentSize = CGSizeMake(0, bottomLY);

}
- (void)payTypeBtnClick:(UIButton *)sender{
    if (sender.selected) {
        return;
    }
    for (UIButton *btn in payTypeArray) {
        if (btn == sender) {
            btn.selected = YES;
        }else{
            btn.selected = NO;
        }
    }
    NSArray *typearr = allArray[0];
    payTypeSelDic = typearr[sender.tag - 1000];
    payTypeID = minstr([payTypeSelDic valueForKey:@"id"]);
    for (int i = 0; i < coinArray.count; i++) {
        UIButton *btn = coinArray[i];
        UILabel *label = (UILabel *)[btn viewWithTag:btn.tag+3000];
        UILabel *moneyLb = (UILabel *)[btn viewWithTag:btn.tag+4000];

        if ([payTypeID isEqual:@"apple"]) {
            label.text = minstr([allArray[1][i] valueForKey:@"coin_ios"]);
            moneyLb.text =[NSString stringWithFormat:@"¥%@",minstr([allArray[1][i] valueForKey:@"money"])];

        }else if ([payTypeID isEqual:@"paypal"]){
            label.text = minstr([allArray[1][i] valueForKey:@"coin_paypal"]);
            moneyLb.text =[NSString stringWithFormat:@"$%@",minstr([allArray[1][i] valueForKey:@"money"])];
        }else{
            label.text = minstr([allArray[1][i] valueForKey:@"coin"]);
            moneyLb.text =[NSString stringWithFormat:@"¥%@",minstr([allArray[1][i] valueForKey:@"money"])];

        }
    }
}
- (void)coinBtnClick:(UIButton *)sender{
    for (UIButton *btn in coinArray) {
        if (btn == sender) {
            //btn.layer.borderColor = Pink_Cor.CGColor;
            [btn setBackgroundImage:[UIImage imageNamed:@"充值-金币"] forState:0];
        }else{
            //btn.layer.borderColor = UIColor.clearColor.CGColor;
            [btn setBackgroundImage:[UIImage imageNamed:@""] forState:0];
        }
    }
    _seleDic = allArray[1][sender.tag-2000];
    if (minstr([payTypeSelDic valueForKey:@"href"]).length > 6) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:minstr([payTypeSelDic valueForKey:@"href"])]];
    }else{
        NSDictionary *payPostDic = @{@"chargeid":minstr([_seleDic valueForKey:@"id"]),
                                     @"coin":minstr([_seleDic valueForKey:@"coin"]),
                                     @"money":minstr([_seleDic valueForKey:@"money"]),//
                                    };
        YBWeakSelf;
        if ([payTypeID isEqual:@"ali"]) {
            [YBRechargeType chargeManeger].aliPayKey = _aliapp_key_ios;
            [YBRechargeType chargeManeger].aliPayPartner = _aliapp_partner;
            [YBRechargeType chargeManeger].aliPaySellerID = _aliapp_seller_id;
            [YBRechargeType chargeManeger].aliCallBackUrl = [h5url stringByAppendingString:@"/appapi/pay/notify_ali"];
            [[YBRechargeType chargeManeger]selAliPayUrl:@"Charge.getAliOrder" andParameter:payPostDic complete:^(int stateCode, int payType, NSString *msg) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (stateCode == 0) {
                        [weakSelf requestData];
                    }
                });
            }];
        }
        if ([payTypeID isEqual:@"wx"]) {
            [YBRechargeType chargeManeger].wechatAppID = _wx_appid;
            [[YBRechargeType chargeManeger]selWechatPayUrl:@"Charge.getWxOrder" andParameter:payPostDic complete:^(int stateCode, int payType, NSString *msg) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (stateCode == 0) {
                        [weakSelf requestData];
                    }
                });
            }];
        }
        if ([payTypeID isEqual:@"apple"]) {
            NSDictionary *iospayPostDic = @{@"chargeid":minstr([_seleDic valueForKey:@"id"]),
                                         @"coin":minstr([_seleDic valueForKey:@"coin_ios"]),
                                         @"money":minstr([_seleDic valueForKey:@"money"]),//
                                        };
            [YBRechargeType chargeManeger].productID = minstr([_seleDic valueForKey:@"product_id"]);
            [YBRechargeType chargeManeger].appleCallBackUrl = [h5url stringByAppendingFormat:@"/appapi/pay/notify_ios"];
            [[YBRechargeType chargeManeger]selApplePayUrl:@"Charge.getIosOrder" andParameter:iospayPostDic complete:^(int stateCode, int payType, NSString *msg) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (stateCode == 0) {
                        [weakSelf requestData];
                    }
                });
            }];
        }
        if ([payTypeID isEqual:@"paypal"]) {
            [[YBRechargeType chargeManeger]selPayPalAndPatameter:payPostDic rechargeType:rechargeType_coin complete:^(int stateCode, int payType, NSString *msg) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (stateCode == 0) {
                        [weakSelf requestData];
                    }
                });

            }];
        }
    }
}
- (void)eula{
    PubH5 *h5VC = [[PubH5 alloc]init];
    h5VC.url = [h5url stringByAppendingString:@"/portal/page/index?id=37"];
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:h5VC animated:YES];
    

}
@end
